const mongoose=require('mongoose');
const Comments=require('../models/comment.model.js');

exports.get=function (req,res,next){
    const id=req.params.id;
    Comments.findById(id,function(err,data){
        res.json(data);
    })
}
//增
exports.create=function (req,res,next) {
    const comments=new Comments(req.body);
    comments.save()
    .then(data=>{
        res.json(data);
    });
}

//改
exports.update=function(req,res,next) {
    const id= req.params.id;
    const comments= new Comments(req.body);
    Comments.findByIdAndUpdate(id,{$set:req.body},{new: false})
    .then(data=>{
        res.json(data)
    })
}

//删
exports.remove = function(req,res,next){
    const id = req.params.id;
    Comments.findByIdAndRemove(id,function(err,data){
        res.json({'message':'数据已删除'})
    })    
}



//删多个
exports.removes = function(req,res,next){
    var ids = req.body.ids;
    ids=ids.split(',');

    if(ids.length>0){
        Comments.remove( { _id: {$in: ids }})
        .then(data=>{
            res.json({'message':'多条评论已删除'});
        })
    }else{
        res.status(404).send({'message':'404'});
    }
}

//查
exports.list=function (req,res,next) {
    var page=(req.body.page) ? req.body.page:1;
    var rows = (req.body.rows) ? req.body.rows : 5;
    var queryCondition = {};
    if(req.body.name && req.body.name.trim().length>0){
        name = req.body.name;
        queryCondition = {
            "name": new RegExp(name,'i')
        }
    }

    if(req.body.title && req.body.title.trim().length>0){
        title=req.body.title;
        queryCondition={
            "title": new RegExp(title,'i')
        }
    }

    Comments.paginate(queryCondition,{page: +page, limit: +rows},function(err, result){
        result.rows = result.docs;
        delete result.docs;
        res.json(result)
    })
}